//index.js
const { Socket } = require("../../utils/socket.js");

const { Shake } = require("../../utils/shake.js");

const app = getApp();

Page({
  data: {
    avatarUrl: "./user-unlogin.png",
    userInfo: {},
    logged: false,
    count: 0,
    status: 'before'
  },

  onLoad: function() {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting["scope.userInfo"]) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo,
                logged: true
              });
            }
          });
        }
      }
    });

    //监听手机摇一摇触发事件
    new Shake({
      threshold: 15,
      onChange: this.shakeEventDidOccur
    });

    this.connect = new Socket({
      onMessage: this.onMessage,
      onConnectMessage: this.onConnectMessage
    });
  },

  onGetUserInfo: function(e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      });
    }
  },

  onMessage: function(msg) {
    console.log("in message");
    console.log(msg);
  },

  onConnectMessage: function({ id }) {
    console.log("in onConnectMessage");
    console.log(id);
    this.setData({
      chatId: id
    });
  },

  shakeEventDidOccur: function() {
    const { count, userInfo } = this.data;
    wx.vibrateShort();
    this.setData(
      {
        count: count + 1
      },
      () => {
        this.connect.emit("yao", {
          userInfo,
          sum: count
        });
      }
    );
  },

  handleTest: function(event) {
    this.shakeEventDidOccur();
  },

  handleStart: function() {
    wx.scanCode({
      onlyFromCamera: false,
      success: (res) => {
        console.log('scan success');
        console.log(res);
      },
      fail: (err) => {

      }
    })
  }
});
